﻿#pragma once
#include <iostream>
using namespace std;
enum Colour
{
	RED,
	BLACK
};

template<class T>
struct RBTreeNode
{
	T _data;
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	Colour _col;
	RBTreeNode(const T& data)
		:_data(data)
		, _left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		,_col(RED)
	{}

};
template<class T,class Ref,class Ptr>
struct RBTreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T, Ref, Ptr> Self;

	Node* _node;
	Node* _root;

	RBTreeIterator(Node* node,Node* root)
		:_node(node)
		,_root(root)
	{}

	// 请完善迭代器的++操作，让迭代器可以移动
	Self& operator++()
	{
		if (_node->_right)
		{
			//如果_node的右子树不为空，中序走到它右子树的左子树的最左（最小）节点
			Node* RLMinNode = _node->_right;
			while (RLMinNode->_left)
			{
				RLMinNode = RLMinNode->_left;
			}
			_node = RLMinNode;
		}
		else
		{
			//右子树为空，走到祖先里面孩子是父亲左的那个祖先
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && parent->_right == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}

	
	Ref operator*()
	{
		return _node->_data;
	}
	Ptr operator->()
	{
		return &_node->_data;
	}

	
	bool operator!=(const Self& s) const
	{
		return _node != s._node;
	}
	bool operator==(const Self& s) const
	{
		return _node == s._node;
	}
};


template<class K, class T, class KeyOfT>
class RBTree
{
	typedef RBTreeNode<T> Node;
public:
	typedef RBTreeIterator<T, T&, T*> Iterator;
	typedef RBTreeIterator<T, const T&, const T*> ConstIterator;

	~RBTree()
	{
		Destroy(_root);
		_root = nullptr;
	}

	Iterator Begin()
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return Iterator(cur, _root);

	}
	Iterator End()
	{
		return Iterator(nullptr, _root);
	}


	ConstIterator Begin() const
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return ConstIterator(cur, _root);

	}
	ConstIterator End() const
	{
		return ConstIterator(nullptr, _root);
	}


	

	// 在红黑树中插入值为data的节点，插入成功返回true，否则返回false
	pair<Iterator, bool> Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_col = BLACK;
			//return pair<Iterator, bool>(Iterator(_root, _root), true);
			return { Iterator(_root, _root), true };
		}
		KeyOfT kot;
		Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (kot(cur->_data) < kot(data))
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (kot(cur->_data) > kot(data))
			{
				parent = cur;
				cur = cur->_left;
			}
			else
				return { Iterator(cur, _root), false };
		}
		cur = new Node(data);
		Node* newnode = cur;

		cur->_col = RED;
		if( kot(cur->_data) < kot(parent->_data) )
		{
			parent->_left = cur;
		}
		else
		{
			parent->_right = cur;
		}
		cur->_parent = parent;
		while(parent && parent->_col == RED)
		{
			Node* grandfather = parent->_parent;
			if (parent == grandfather->_left)
			{
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED)
				{
					//     g
					//  p      u 
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					//     g
					//  p      u 
					//c
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//       g
						//   p       u 
						//     c
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;

					} 
					break;
				}

			}
			else
			{
				//     g
				//  u      p
				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED)
				{
					//     g
					//  u     p
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					//     g
					//  u     p 
					//           c
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//       g
						//   u       p 
						//         c
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}

			}
		}
		_root->_col = BLACK;
		return { Iterator(newnode, _root), true };
	}

	// 检测红黑树中是否存在值为data的节点，存在返回该节点的地址，否则返回nullptr
	Node* Find(const T& data)
	{
		if (_root == nullptr)
		{
			return nullptr;
		}
		Node* cur = _root;
		while (cur)
		{
			if (data > cur->_data)
			{
				
				cur = cur->_right;
			}
			else if (data < cur->_data)
			{
				
				cur = cur->_left;
			}
			else
				return cur;
		}
		return nullptr;
	}

	// 获取红黑树最左侧节点
	Node* LeftMost()
	{
		if (_root == nullptr)
			return nullptr;
		Node* cur = _root;
		while (cur->_left)
		{
			cur = cur->_left;
		}
		return cur;
	}

	// 获取红黑树最右侧节点
	Node* RightMost()
	{
		if (_root == nullptr)
			return nullptr;
		Node* cur = _root;
		while (cur->_right)
		{
			cur = cur->_right;
		}
		return cur;
	}

	//// 检测红黑树是否为有效的红黑树，注意：其内部主要依靠_IsValidRBTRee函数检测
	//bool IsValidRBTRee()
	//{
	//	if (_root == nullptr)
	//		return true;

	//	if (_root->_col == RED)
	//		return false;

	//	size_t pathBlack = 0;
	//	Node* cur = _root;
	//	while (cur)
	//	{
	//		if (cur->_col == BLACK)
	//		{
	//			++pathBlack;
	//		}
	//		cur = cur->_left;
	//	}

	//	return _IsValidRBTRee(_root, 0, pathBlack);
	//}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

	int Height()
	{
		return _Height(_root);
	}

	int Size()
	{
		return _Size(_root);
	}
private:

	void Destroy(Node* root)
	{
		if (root == nullptr)
			return;

		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr)
			return;
		_InOrder(root->_left);
		cout << root->_data << " ";
		_InOrder(root->_right);

	}
	int _Height(Node* root)
	{
		if (root == nullptr)
			return 0;
		int LeftHeight = _Height(root->_left);
		int RightHeight = _Height(root->_right);
		return LeftHeight > RightHeight ? LeftHeight + 1 : RightHeight + 1;
	}
	int _Size(Node* root)
	{
		if (root == nullptr)
			return 0;
		int LeftSize = _Size(root->_left);
		int RightSize = _Size(root->_right);
		return LeftSize + RightSize + 1;

	}
	/*bool _IsValidRBTRee(Node* root, size_t blackCount, size_t pathBlack)
	{
		if (root == nullptr) 
		{
			if (blackCount != pathBlack)
			{
				cout << "存在黑色结点的数量不相等的路径" << endl;
				return false;
			}
			return true;
		}

		if (root->_col == RED && root->_parent->_col == RED)
		{
			cout << "存在连续的红色结点" << endl;
			return false;
		}

		if (root->_col == BLACK)
		{
			blackCount++;
		}

		return _IsValidRBTRee(root->_left, blackCount, pathBlack)
			&& _IsValidRBTRee(root->_right, blackCount, pathBlack);
	}*/
	// 左单旋
	void RotateL(Node* parent)
	{
		Node* childR = parent->_right;
		Node* childRL = childR->_left;
		parent->_right = childRL;
		if (childRL)
			childRL->_parent = parent;
		childR->_left = parent;
		Node* grandparent = parent->_parent;
		parent->_parent = childR;
		if (grandparent == nullptr)
		{
			_root = childR;
			childR->_parent = nullptr;

		}
		else
		{
			if (parent == grandparent->_left)
			{
				grandparent->_left = childR;
			}
			else
			{
				grandparent->_right = childR;
			}
			childR->_parent = grandparent;
		}
	}
	// 右单旋
	void RotateR(Node* parent)
	{
		Node* childL = parent->_left;
		Node* childLR = childL->_right;
		parent->_left = childLR;
		if (childLR)
			childLR->_parent = parent;
		childL->_right = parent;
		Node* grandparent = parent->_parent;
		parent->_parent = childL;
		if (grandparent == nullptr)
		{
			_root = childL;
			childL->_parent = nullptr;

		}
		else
		{
			if (parent == grandparent->_left)
			{
				grandparent->_left = childL;
			}
			else
			{
				grandparent->_right = childL;
			}
			childL->_parent = grandparent;
		}
	}
	// 为了操作树简单起见：获取根节点
	Node*& GetRoot()
	{
		return _root;
	}
	
private:
	Node* _root = nullptr;
};

